<template>
  <Modal
    :options="getModalOptions"
    :on-positive-click="handleConfirm"
    :on-negative-click="handleClose"
    :on-close="handleClose"
  >
    <template #Context>
      <n-form
        ref="formRef"
        :model="userForm"
        :rules="userRules"
        :label-width="100"
        label-placement="left"
        require-mark-placement="left"
        :disabled="type === 'preview'"
      >
        <template v-for="(item,index) in getFormOptions" :key="index">

          <n-form-item v-if="item.type == 'input'" :label="item.label" :path="item.key">
            <n-input v-model:value="userForm[item.key]" type="textarea" v-bind="item.props" />
          </n-form-item>
          <n-form-item v-if="item.type === 'oss'" :label="item.label" :path="item.key">
            <fileOss v-if="item.type === 'oss'" :ref="el=>{ossRefs[item.refIndex] = el}" :default-list="userForm[item.file]" @upload-status="handleUploadStatus" />
          </n-form-item>

        </template>
      </n-form>
    </template>
  </Modal>

</template>

<script>
import { defineComponent, ref, reactive, computed, toRefs } from 'vue'
import { form } from '../tools/form.js'
import Modal from '@/components/Modal/index.vue'
import fileOss from '@/components/UploadOss/index.vue'
import { useUserStore } from '@/store/modules/user'
import { orderInspection } from '@/api/order-work/index'

export default defineComponent({
  name: 'UserModal',
  components: { Modal, fileOss },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      default: 'create'
    },
    data: {
      type: Object,
      default: () => null
    }
  },
  emits: {
    'update:visible': null,
    'reload': null
  },
  setup(props, { emit }) {
    const MODAL_TYPE = {
      'create': '处理问题',
      'preview': '详情'
    }
    const roleType = useUserStore().userInfo.type // 1：超级管理员， 2：管理员， 3：普通用户

    const { formItem, userForm, userRules } = form
    const formRef = ref()

    const data = reactive({
      userForm: {
        ...userForm,
        ...props.data
      },
      userRules: {
        ...userRules
      }
    })
    const getModalOptions = computed(() => {
      return {
        show: props.visible,
        title: MODAL_TYPE[props.type],
        negativeText: '取消',
        positiveText: '确认'
      }
    })

    if (props.type === 'preview') {
      data.userForm.handlerImage = data.userForm.handlerImages
    }

    const getFormOptions = computed(() => {
      return {
        ...formItem
      }
    })

    const ossRefs = ref([])
    function handleUploadStatus(status) {
      switch (status) {
        case 'no-file':
          data.userForm.imageStatus = ''
          break
        default:
          data.userForm.imageStatus = status
      }
    }

    function handleConfirm() {
      if (props.type === 'preview') {
        handleClose()
        return
      }
      formRef.value?.validate(async(errors) => {
        if (!errors) {
          const uploads = ossRefs.value.map((item, index) => {
            return item.startUpload()
          })
          Promise.all(uploads)
            .then(response => {
              const isError = response.map((item) => {
                return item.includes('error')
              })
              if (!isError.includes(true)) {
                const imageStr = response.join()
                const params = {
                  ...data.userForm,
                  handlerImage: imageStr
                }
                if (props.type === 'create') {
                  orderInspection(params).then(res => {
                    if (res.code === 0) {
                      emit('reload')
                      handleClose()
                    }
                  })
                } else {
                // 详情
                  handleClose()
                }
              }
            })
        } else {
          $message.error('请完善必填信息')
        }
      })
    }

    /* 关闭弹窗 */
    const handleClose = () => {
      emit('update:visible', false)
    }

    const fileLen = props.data.fileImage ? props.data.fileImage.split(',') : 0

    return {
      ...toRefs(data),
      formRef,
      getModalOptions,
      getFormOptions,
      handleConfirm,
      handleClose,
      roleType,
      ossRefs,
      handleUploadStatus,
      fileLen
    }
  }
})
</script>

<style lang="scss" scoped>
</style>
